package org.lcc.Controller.exception;

import org.lcc.util.ApiResponseMe;
import org.lcc.model.entity.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局异常处理器
 * 用于统一处理项目中的异常，提高代码的健壮性和可维护性
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * 当项目中抛出BusinessException时，该方法将被调用
     * 业务异常是指在业务逻辑处理过程中，由于特定业务规则被违反而人为抛出的异常
     *
     * @param e 业务异常对象
     * @return 包含错误信息的响应实体
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ApiResponseMe> handleBusinessException(BusinessException e) {
        ApiResponseMe response = new ApiResponseMe();
        response.setCode(e.getCode());
        response.setMessage(e.getMessage());
        response.setData(null);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }


    /**
     * 处理所有类型的异常
     * 当项目中抛出任何异常时，该方法将被调用
     *
     * @param e 异常对象
     * @return 包含错误信息的响应实体
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponseMe> handleException(Exception e) {
        ApiResponseMe response = new ApiResponseMe();
        response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        e.printStackTrace();
        response.setMessage("内部服务器错误");
        response.setData(null);
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }


}
